package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.List;

@Aspect
@Slf4j
@Component
public class AutoFillAspect {
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut(){}


    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint){
        log.info("开始进行数据填充");
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = methodSignature.getMethod().getAnnotation(AutoFill.class);
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0){
            return;
        }
        Object entry = args[0];
        OperationType operationType = autoFill.value();
        LocalDateTime now = LocalDateTime.now();
        Long id = BaseContext.getCurrentId();
        
        // 如果参数是List类型，需要特殊处理
        if (entry instanceof List) {
            List<?> list = (List<?>) entry;
            if (!list.isEmpty()) {
                // 对列表中的每个元素进行填充
                for (Object obj : list) {
                    fillEntityFields(obj, operationType, now, id);
                }
            }
            return;
        }
        
        // 单个实体对象的处理
        fillEntityFields(entry, operationType, now, id);
    }
    
    /**
     * 填充实体对象的公共字段
     * @param entity 实体对象
     * @param operationType 操作类型
     * @param now 当前时间
     * @param userId 当前用户ID
     */
    private void fillEntityFields(Object entity, OperationType operationType, LocalDateTime now, Long userId) {
        if (operationType == OperationType.INSERT){
            try {
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                setUpdateTime.invoke(entity, now);
                setUpdateUser.invoke(entity, userId);
                setCreateTime.invoke(entity, now);
                setCreateUser.invoke(entity, userId);
            } catch (Exception e) {
                // 忽略没有这些方法的实体类
                log.debug("实体类 {} 没有公共字段方法: {}", entity.getClass().getSimpleName(), e.getMessage());
            }
        }else if (operationType == OperationType.UPDATE){
            try {
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setUpdateTime.invoke(entity, now);
                setUpdateUser.invoke(entity, userId);
            } catch (Exception e) {
                // 忽略没有这些方法的实体类
                log.debug("实体类 {} 没有公共字段方法: {}", entity.getClass().getSimpleName(), e.getMessage());
            }
        }
    }
}